import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'mop_ext_wechat_handlers.dart';
import 'mop_ext_wechat_platform_interface.dart';
import 'dart:convert';

/// An implementation of [MopExtWechatPlatform] that uses method channels.
class MethodChannelMopExtWechat extends MopExtWechatPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('mop_ext_wechat');

  MethodChannelMopExtWechat() {
    methodChannel.setMethodCallHandler(_handleMethodCall);
  }
  
  /// 处理来自原生的调用
  Future<dynamic> _handleMethodCall(MethodCall call) async {
    switch (call.method) {
      case 'forwardApplet':
      case 'getUserInfo':
      case 'getUserProfile':
      case 'contact':
      case 'getPhoneNumber':
      case 'launchApp':
      case 'feedback':
      case 'chooseAvatar':
        return await _handleHandlerMethodCall(call);
      case 'hasMethod':
        return _hasMethod(call.arguments['methodName']);
      default:
        return null;
    }
  }

  bool _hasMethod(String methodName) {
    if (handlers == null) {
      return false;
    }

    MopExtWechatHandlers h = handlers!;
    switch (methodName) {
      case 'forwardApplet':
        return h.forwardAppletHandler != null;
      case 'getUserInfo':
        return h.getUserInfoHandler != null;
      case 'getUserProfile':
        return h.getUserProfileHandler != null;
      case 'contact':
        return h.contactHandler != null;
      case 'getPhoneNumber':
        return h.getPhoneNumberHandler != null;
      case 'launchApp':
        return h.launchAppHandler != null;
      case 'feedback':
        return h.feedbackHandler != null;
      case 'chooseAvatar':
        return h.chooseAvatarHandler != null;
      default:
        return false;
    }
  }

  Future<dynamic> _handleHandlerMethodCall(MethodCall call) async {

    Map<String, dynamic> result = {
      // flutter端是否设置的hander
      'success': false
    };
    if (handlers == null) {
      return result;
    }
    MopExtWechatHandlers h = handlers!;

    Map<String, dynamic> mapParams = _decodeParams(call.arguments);
    Map<String, dynamic> appletInfo = mapParams['appletInfo'];
    switch (call.method) {
      case 'forwardApplet':

        MopExtWechatForwardAppletHandler? handler = h.forwardAppletHandler;
        if (handler != null) {
           var handlerResult = await handler.forwardApplet(appletInfo);
           result['success'] = handlerResult.success;
           return result;
        }
        return result;
      case 'getUserInfo':
        MopExtWechatGetUserInfoHandler? handler = h.getUserInfoHandler;
        if (handler  != null) {
          var handlerResult = await handler.getUserInfo(appletInfo);
          result['success'] = handlerResult.success;
          result['data'] = handlerResult.data;
          return result;
        }
        return result;
      case 'getUserProfile':
        MopExtWechatGetUserProfileHandler? handler = h.getUserProfileHandler;
        if (handler != null) {
          var handlerResult = await handler.getUserProfile(appletInfo);
          result['success'] = handlerResult.success;
          result['data'] = handlerResult.data;
          return result;
        }
        return result;
      case 'contact':


        MopExtWechatContactHandler? handler = h.contactHandler;
        if (handler != null) {
          var handlerResult = await handler.contact(
            appletInfo,
            mapParams['sessionFrom'] as String,
            mapParams['sendMessageTitle'] as String,
            mapParams['sendMessagePath'] as String,
            mapParams['sendMessageImg'] as String,
            mapParams['showMessageCard'] as bool,
          );
          result['success'] = handlerResult.success;
          return result;
        }
        return result;
      case 'getPhoneNumber':
        MopExtWechatGetPhoneNumberHandler? handler = h.getPhoneNumberHandler;
        if (handler != null) {
          var handlerResult = await handler.getPhoneNumber(appletInfo);
          result['success'] = handlerResult.success;
          result['data'] = handlerResult.data;
          return result;
        }
        return result;
      case 'launchApp':

        MopExtWechatLaunchAppHandler? handler = h.launchAppHandler;
        if (handler != null) {
          var handlerResult = await handler.launchApp(appletInfo, mapParams['appParameter'] as String);
          result['data'] = handlerResult.data;
          result['success'] = handlerResult.success;
          return result;
        }
        return result;
      case 'feedback':
        MopExtWechatFeedbackHandler? handler = h.feedbackHandler;
        if (handler != null) {
          var handlerResult = await handler.feedback(appletInfo);
          result['success'] = handlerResult.success;
          return result;
        }
        return result;
      case 'chooseAvatar':
        MopExtWechatChooseAvatarHandler? handler = h.chooseAvatarHandler;
        if (handler != null) {
          var handlerResult = await handler.chooseAvatar(appletInfo);
          result['data'] = handlerResult.data;
          result['success'] = handlerResult.success;
          return result;
        }
        return result;
      default:
        return null;
    }
  }

  Map<String, dynamic> _decodeParams(String jsonString) {
    Map<String, dynamic> params = {};
    try {
      params = json.decode(jsonString);
    } catch (e) {
      print('JSON 解析失败: $e');
    }
    return params;
  }


  /// 注册组件
  ///
  /// [wxAppId] 应用在微信开放平台注册的appId
  /// [universalLink] universalLink
  ///
  /// 返回初始化是否成功
  @override
  Future<Map> registerComponent({
    required String wxAppId,
    required String universalLink,
  })  async {
    // 调用原生方法通道
    final Map result = await methodChannel.invokeMethod(
      'registerComponent',
      {
        'wxAppId': wxAppId,
        'universalLink': universalLink,
      },
    );

    return result;
  }

}
